package cn.edu.zhku.controller;

import cn.edu.zhku.aspect.annotation.CheckNoExist;
import cn.edu.zhku.aspect.annotation.CheckUsernameExist;
import cn.edu.zhku.constant.ResponseCode;
import cn.edu.zhku.dto.UserDto;
import cn.edu.zhku.pojo.Token;
import cn.edu.zhku.pojo.User;
import cn.edu.zhku.service.UserService;
import cn.edu.zhku.shiro.service.ShiroService;
import cn.edu.zhku.swagger.notes.ShiroApiNotes;
import cn.edu.zhku.util.ResultUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/api")
public class ShiroController {

    @Autowired
    private ShiroService shiroService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录接口", notes = ShiroApiNotes.login)
    @PostMapping("/login")
    public JSONObject login(@RequestBody UserDto userDto) {
        User userPojo = userDto.getUser();
        String username = userPojo.getUsername();
        String password = userPojo.getPassword();
        User user = this.userService.findPasswordAndSaltByUsername(username);
        // 账号不存在
        if (user == null)
            return ResultUtil.getResult(ResponseCode.unauthenticated, "用户名或密码错误，请重新登录");
        String credential = new Md5Hash(password, user.getSalt(), 1024).toString();
        // 密码错误
        if (!credential.equals(user.getPassword()))
            return ResultUtil.getResult(ResponseCode.unauthenticated, "用户名或密码错误，请重新登录");
        // 生成token，并保存到数据库
        Token token = this.shiroService.getToken(user.getUserId());
        JSONObject result = ResultUtil.getResult(ResponseCode.ok, "登录成功");
        result.put("token", token.getToken());
        return result;
    }

    @CheckUsernameExist
    @CheckNoExist
    @PostMapping("/signup")
    @ApiOperation(value = "注册接口", notes = ShiroApiNotes.signup)
    public JSONObject signup(@RequestBody UserDto userDto) {
        User user = userDto.getUser();
        String salt = UUID.randomUUID().toString();
        String credential = new Md5Hash(user.getPassword(), salt, 1024).toString();
        user.setPassword(credential);
        user.setSalt(salt);
        this.userService.addOne(user);
        return ResultUtil.getResult(ResponseCode.ok, "注册学生用户成功");
    }

    @PostMapping("/logout")
    @ApiOperation(value = "登出接口", notes = ShiroApiNotes.logout)
    public JSONObject logout(@RequestHeader("token") String token) {
        this.shiroService.logout(token);
        return ResultUtil.getResult(ResponseCode.ok, "您已安全退出系统");
    }

}
